package com.dgt.trade.controller;

import com.dgt.trade.entitys.*;
import com.dgt.trade.entitys.trade.Product;
import com.dgt.trade.entitys.yifu.Subaccounts_banks;
import com.dgt.trade.entitys.yifu.Subaccounts_password;
import com.dgt.trade.entitys.yifu.Subaccounts_select;
import com.dgt.trade.service.*;
import com.dgt.trade.utils.HttpClientUtil;
import com.dgt.trade.utils.MapToStringSplicing;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.dgt.trade.utils.ConstantsUtils;
import com.dgt.trade.utils.MD5Util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;

    @Autowired
    private UserBalanceService userBalanceService;

    @Autowired
    private TradeService tradeService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private PromotionService promotionService;

    @RequestMapping("/index")
    public ModelAndView index(Model model) {
        User user = getUser(request);
        ModelAndView view = new ModelAndView();

        Integer status = null;
        String message = null;
        String SubAccountID = null;
        String SubAccountName = null;
        String AgentName = null;
        String Link = null;
        String SubLink = null;
        String time = String.valueOf(new Date().getTime());

        if (user != null) {

            //逸富查询子账户
            Map<String, String> select_map = new LinkedHashMap<String, String>();
            Subaccounts_select subaccounts_select = new Subaccounts_select();
            subaccounts_select.setParams(user.getMobile());
            subaccounts_select.setType("1");
            subaccounts_select.setTimeStamp(time);
            subaccounts_select.setVersion("1.0");
            String MD5 = MD5Util.MD5(subaccounts_select.getParams(), subaccounts_select.getType(), subaccounts_select.getTimeStamp(), subaccounts_select.getVersion());
            subaccounts_select.setSignMsg(MD5);

            select_map.put("Params", subaccounts_select.getParams());
            select_map.put("Type", subaccounts_select.getType());
            select_map.put("TimeStamp", subaccounts_select.getTimeStamp());
            select_map.put("Version", subaccounts_select.getVersion());
            select_map.put("SignMsg", subaccounts_select.getSignMsg());

            String query = MapToStringSplicing.createLinkStringByGet(select_map);

            try {
                String result = HttpClientUtil.getProcessDefinitionList("http://120.55.162.84:8050/api/subaccounts?" + query, select_map);
                JsonParser parser = new JsonParser();
                JsonObject object = (JsonObject) parser.parse(result);
                JsonArray array = null;
                JsonObject subObject = null;
                status = object.get("status").getAsInt();
                if (status == 0) {
                    array = object.get("data").getAsJsonArray();
                    for (int i = 0; i < array.size(); i++) {
                        subObject = array.get(i).getAsJsonObject();
                        SubAccountID = subObject.get("SubAccountID").getAsString();
                        SubAccountName = subObject.get("SubAccountName").getAsString();
                        AgentName = subObject.get("AgentName").getAsString();
                        Link = subObject.get("Link").getAsString();
                        SubLink = subObject.get("SubLink").getAsString();
                    }
                } else {
                    message = object.get("message").getAsString();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            view.getModel().put("SubAccountID", SubAccountID);
            model.addAttribute("user", user);
            view.setViewName("user/index");
        } else {
            view.setViewName("user/weidenglu");
        }
        return view;
    }

    @RequestMapping("/accountCenter")
    public ModelAndView accountCenter() {
        ModelAndView view = new ModelAndView();
        Object obj = request.getSession().getAttribute(ConstantsUtils.LOGIN_KEY_FLAG);
        User user = JSON.parseObject((String) obj, User.class);
        if (user != null) {
            view.addObject("user", user);
            view.setViewName("user/account");
        } else {
            view.setViewName("error/404");
        }
        return view;
    }

    @RequestMapping("/updatePwd")
    public ModelAndView updatePwd(String mobile, String oldPwd, String newPwd) {
        ModelAndView mav = new ModelAndView();
        Object obj = request.getSession().getAttribute(ConstantsUtils.LOGIN_KEY_FLAG);
        User user1 = JSON.parseObject((String) obj, User.class);
        mav.addObject("user", user1);
        String time = String.valueOf(new Date().getTime());
        Integer status = null;
        String message = null;

        User user = userService.getMemberByMobile(mobile);

        if (user != null && MD5Util.MD5(user.getMobile(), oldPwd).equals(user.getPassword())) {

            //逸富重置密码
            Map<String, String> map = new LinkedHashMap<String, String>();
            Subaccounts_password subaccountsPassword = new Subaccounts_password();
            subaccountsPassword.setPassword(newPwd);
            subaccountsPassword.setSubAccountID(user.getSubAccountID());
            subaccountsPassword.setTimeStamp(time);
            subaccountsPassword.setVersion("1.0");
            String str = MD5Util.MD5_password(subaccountsPassword.getPassword(), subaccountsPassword.getSubAccountID(), subaccountsPassword.getTimeStamp(), subaccountsPassword.getVersion());
            subaccountsPassword.setSignMsg(str);

            map.put("Password", subaccountsPassword.getPassword());
            map.put("SubAccountID", subaccountsPassword.getSubAccountID());
            map.put("TimeStamp", subaccountsPassword.getTimeStamp());
            map.put("Version", subaccountsPassword.getVersion());
            map.put("SignMsg", subaccountsPassword.getSignMsg());

            String query = MapToStringSplicing.createLinkStringByGet(map);

            String result = null;
            try {
                result = HttpClientUtil.postHistoryProcessInstancesList("http://120.55.162.84:8050/api/subaccounts/password?" + query, map);
                JsonParser parser = new JsonParser();
                JsonObject object = (JsonObject) parser.parse(result);
                JsonArray array = null;
                JsonObject subObject = null;
                status = object.get("status").getAsInt();
                message = object.get("message").getAsString();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (status == 0) {
                boolean i = userService.updatePwdbyMobile(user.getMobile(), newPwd);
                System.out.println(i);
            } else {
                mav.addObject("msg", "【逸富】重置密码错误");
                mav.setViewName("user/change_pass");
            }
        } else {
            mav.addObject("msg", "原密码错误");
            mav.setViewName("user/change_pass");
            return mav;
        }
        request.getSession().setAttribute(ConstantsUtils.LOGIN_KEY_FLAG, null);
        mav.setViewName("/user/weidenglu");
        return mav;
    }

    @RequestMapping("/toUpdatePwd")
    public ModelAndView toUpdatePwd() {
        ModelAndView view = new ModelAndView();
        Object obj = request.getSession().getAttribute(ConstantsUtils.LOGIN_KEY_FLAG);
        User user = JSON.parseObject((String) obj, User.class);
        if (user != null) {
            view.addObject("user", user);
            view.setViewName("user/change_pass");
        } else {
            view.setViewName("error/404");
        }
        return view;
    }

    @RequestMapping("/toMyuser")
    public ModelAndView toMyuser(Model model) {
        ModelAndView view = new ModelAndView();
        /*User u = getUser(request);
        List<Promotion> promotionList = promotionService.selectPromotionById((int) u.getId());
        User user = userService.getMemberById(u.getId());
        if (promotionList != null || user != null) {
            model.addAttribute("user", user);
            view.getModel().put("promotionList", promotionList);*/
        view.setViewName("user/myuser");
        /*} else {
            view.setViewName("error/404");
        }*/
        return view;
    }

    @RequestMapping("/toFast_orderSet")
    public ModelAndView toFast_orderSet() {
        ModelAndView view = new ModelAndView();
        List<Product> products = tradeService.getProducts();
        if (products != null) {
            view.getModel().put("products", products);
            view.setViewName("user/fast_orderSet");
        } else {
            view.setViewName("error/404");
        }
        return view;
    }

    @RequestMapping("/toCapital")
    public ModelAndView toCapital() {
        ModelAndView view = new ModelAndView();
        User user = getUser(request);
        int user_id = (int) user.getId();
        String data_type = request.getParameter("data_type");
        if (data_type == null || data_type.equals("0")) {
            data_type = "";
        }
        List<UserBalance> userBalance = userBalanceService.getUserBalanceById(user_id, "%" + data_type + "%");
        if (userBalance != null) {
            view.addObject("user", userBalance);
            view.setViewName("user/count_list");
        } else {
            view.setViewName("error/404");
        }
        return view;
    }

    @RequestMapping("/toUnbund")
    public ModelAndView toUnbund() {
        ModelAndView view = new ModelAndView();
        view.setViewName("user/unbund");
        return view;
    }

    @RequestMapping("/toTixian")
    public ModelAndView ToTiXian() {
        ModelAndView view = new ModelAndView();
        String time = String.valueOf(new Date().getTime());
        Integer status = null;
        String message = null, BankName = null, Name = null, BankAccount = null;
        User user = getUser(request);

        Map<String, String> select_bank = new LinkedHashMap<String, String>();
        Subaccounts_banks subaccounts_banks = new Subaccounts_banks();
        subaccounts_banks.setSubAccountID(user.getSubAccountID());
        subaccounts_banks.setTimeStamp(time);
        subaccounts_banks.setVersion("1.0");
        String msg = MD5Util.MD5_bank(subaccounts_banks.getSubAccountID(), subaccounts_banks.getTimeStamp(), subaccounts_banks.getVersion());
        subaccounts_banks.setSignMsg(msg);

        select_bank.put("SubAccountID", subaccounts_banks.getSubAccountID());
        select_bank.put("TimeStamp", subaccounts_banks.getTimeStamp());
        select_bank.put("Version", subaccounts_banks.getVersion());
        select_bank.put("SignMsg", subaccounts_banks.getSignMsg());

        String query2 = MapToStringSplicing.createLinkStringByGet(select_bank);

        String result1 = null;
        try {
            result1 = HttpClientUtil.getProcessDefinitionList("http://120.55.162.84:8050/api/subaccounts/banks?" + query2, select_bank);
            JsonParser parser = new JsonParser();
            JsonObject object = (JsonObject) parser.parse(result1);
            JsonArray array = null;
            JsonObject subObject = null;
            status = object.get("status").getAsInt();
            if (status == 0) {
                array = object.get("data").getAsJsonArray();
                for (int i = 0; i < array.size(); i++) {
                    subObject = array.get(i).getAsJsonObject();
                    BankName = subObject.get("BankName").getAsString();//	银行名称
                    Name = subObject.get("Name").getAsString();//	姓名
                    BankAccount = subObject.get("BankAccount").getAsString();//	银行卡号
                }
            } else {
                message = object.get("message").getAsString();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (status == 0) {
            view.getModel().put("BankName", BankName);
            view.getModel().put("Name", Name);
            String str = BankAccount.replace(" ", "").substring(BankAccount.replace(" ", "").length() - 4, BankAccount.replace(" ", "").length());
            view.getModel().put("BankAccount", str);
            view.getModel().put("user", user);
            view.setViewName("user/tixian");
        } else {
            System.out.println(message);
            view.setViewName("error/404");
        }
        return view;
    }

    @RequestMapping("/toBdyhk")
    public ModelAndView Tobdyhk() {
        ModelAndView view = new ModelAndView();
        view.setViewName("user/bdyhk");
        return view;
    }

    @RequestMapping("/toTxyhk")
    public ModelAndView Totxyhk() {
        ModelAndView view = new ModelAndView();
        view.setViewName("user/txyhk");
        return view;
    }

    @RequestMapping("/tochangjian")
    public ModelAndView Tochangjian() {
        ModelAndView view = new ModelAndView();
        List<Question> questionList = questionService.selectQuestion();
        List<QuestionType> questionTypes = questionService.selectQuestionType();
        if (questionList != null && questionTypes != null) {
            view.getModel().put("question", questionList);
            view.getModel().put("questionTypes", questionTypes);
            view.setViewName("user/changjian");
        } else {
            view.setViewName("error/404");
        }
        return view;
    }

}
